<?php

namespace backend\modules\goods\controllers;

use backend\modules\base\controllers\BaseController;
use backend\modules\goods\models\Attrvalue;
use backend\modules\goods\models\Goods;
use Yii;
use backend\modules\goods\models\Attribute;
use backend\modules\goods\models\search\AttributeSearch;
use yii\base\Exception;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * AttributeController implements the CRUD actions for Attribute model.
 */
class AttributeController extends BaseController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => [ 'index','sort','create','view','update','del','shiptochange','downtoadd'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Attribute models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new AttributeSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Attribute model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Attribute model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Attribute();
        $attrcatAlias = $model->attrcatAlias('all');
        $postData = Yii::$app->request->post();

        $db = Yii::$app->db;
        $beginTransaction = $db->beginTransaction();
        try{
            if ($model->load($postData) && $model->save()) {
                //分解
                $text = $postData['Attribute']['attrValue'];
                if($text){
                    $arr  = explode("\r\n", $text);
                    //批量插入
                    if($arr){
                        foreach($arr as $k=>$v){
                            $attrValue = new Attrvalue();
                            $attrValue->attr_id = $model->attr_id;
                            $attrValue->attr_value_name = $v;
                            if(!$attrValue->save()){
                                throw new Exception(json_encode($attrValue->errors));
                            }
                        }
                    }
                }
                $beginTransaction->commit();
                return $this->redirect(['update', 'id' => $model->attr_id]);
            }
        }catch (Exception $e){
            $beginTransaction->rollBack();
            return $e->getMessage();
        }
        return $this->render('create', [
            'model' => $model,
            'attrcatAlias'=>$attrcatAlias,
        ]);
    }

    /**
     * Updates an existing Attribute model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        //选中显示页面
        $FormPage = isset($_GET['whiceForm'])?$_GET['whiceForm']:'FormPage01';
        $postData = Yii::$app->request->post();

        $db = Yii::$app->db;
        $beginTransaction = $db->beginTransaction();
        try{
            if ($model->load($postData) && $model->save()) {
                //分解
                $text = $postData['Attribute']['attrValue'];
                if($text){
                    Attrvalue::deleteAll(['attr_id'=>$id]);
                    $arr  = explode("\r\n", $text);
                    //批量插入
                    if($arr){
                        foreach($arr as $k=>$v){
                            $attrValue = new Attrvalue();
                            $attrValue->attr_id = $model->attr_id;
                            $attrValue->attr_value_name = $v;
                            if(!$attrValue->save()){
                                throw new Exception(json_encode($attrValue->errors));
                            }
                        }
                    }
                }
                $beginTransaction->commit();
                return $this->redirect(['update', 'id' => $model->attr_id]);
            }
        }catch (Exception $e){
            $beginTransaction->rollBack();
            return $e->getMessage();
        }

        return $this->render('update', [
            'model' => $model,
            'FormPage'=>$FormPage
        ]);
    }

    /**
     * Deletes an existing Attribute model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Attribute model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Attribute the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Attribute::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
